# -*- coding:utf-8 -*-

import time
import threading
from module.log import Log
from module.handle import Handle

# 日志系统
log = Log()

# 剩下多少任务
over = 10

def main():
    global over

    # 日志同步写线程
    threading.Thread(target=sync).start()

    # 任务栈
    while(True):
        time.sleep(3)
        print("剩余任务数: %i, 当前线程数: %i" % (over, threading.active_count()))

        # 没有剩余任务, 并且任务线程也执行完
        if(over<1 and threading.active_count()==1):
            break

        # 如果没有剩余任务, 但是任务线程却还在执行, 那么就有可能注册失败产生任务
        if(over < 1):
            continue

        # 用户线程 = 所有线程 - 1
        if(threading.active_count() <= 10):
            over -= 1
            threading.Thread(target=run).start()

    sync()

def run():
    handle = Handle()
    status = handle.reg()

    if(status > 0):
        log.add("[%i] %s-%s-%s" % (1, handle.user, handle.pwd, handle.email))
    else:
        global over
        over += 1
        log.add("[%i] %s-%s-%s-%s" % (status, handle.user, handle.pwd, handle.email, handle.errorMsg(status)))

    print("任务执行完毕")

# 同步写日志
def sync():
    time.sleep(20)
    log.sync()

if __name__ == "__main__":
    main()

